package logic;

import java.awt.Color;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateXlsx {
	
	/**
	 * 用于缓存单元格格式.
	 */
	private static final Map<Integer, XSSFCellStyle> CACHE = new HashMap<>();

	/**
	 * 生成成品Excel.
	 * @param list
	 * @param path
	 * @throws Exception
	 */
	static void create(List<int[]> list, String path) throws Exception {
		FileOutputStream out = null;
		XSSFWorkbook excel = null;
		try {
			// 先保存一个空Excel文件，在磁盘占位
			out = new FileOutputStream(path);
			excel = new XSSFWorkbook();
			excel.createSheet("myLove");
			excel.write(out);
			excel.close();
			out.close();

			int size = list.size();
			int length = list.get(0).length;

			// 读取占位的文件，设置列宽
			System.out.println("Loading…");
			excel = new XSSFWorkbook(new FileInputStream(path));
			XSSFSheet sht = excel.getSheetAt(0);
			for (int j = 0; j < length; j++) {
				sht.setColumnWidth(j, (short) 500);
			}

			// 缓存所需的所有单元格格式
			for (int i = 0; i < size; i++) {
				int[] rgbs = list.get(i);
				for (int rgb : rgbs) {
					if (CACHE.get(rgb) == null) {
						XSSFCellStyle style = excel.createCellStyle();
						style.setFillForegroundColor(new XSSFColor(new Color(rgb)));
						style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
						CACHE.put(rgb, style);
					}
				}
			}
			
			if (CACHE.size() > 64000) {
				throw new Exception("图片色彩过于丰富，超出excel格式能容纳的颜色数量上限");
			}

			// 开始按行填充颜色
			for (int i = 0; i < size; i++) {
				System.out.println(i);// 提示行数
				int[] rgbs = list.get(i);
				Row row = sht.createRow(i);
				// 设置行高，使之与列宽相等（即：设置单元格为正方形）
				row.setHeight((short) 250);
				for (int j = 0; j < length; j++) {
					row.createCell(j).setCellStyle(CACHE.get(rgbs[j]));
				}
			}

		} catch (Exception e) {
			throw e;
		} finally {
			out = new FileOutputStream(path);
			excel.write(out);
			excel.close();
			out.close();
			System.out.println("done");// 提示完成
		}
	}
	
}